package com.lancoo.examview.test.presenter;

import android.text.TextUtils;
import android.util.Log;

import com.lancoo.answer.model.eventBean.AudioUpLoadCallBackEventBean;
import com.lancoo.answer.model.eventBean.AudioUpLoadEventBean;
import com.lancoo.answer.model.eventBean.ImageCallBackEventBean;
import com.lancoo.answer.model.eventBean.ImageEventBean;
import com.lancoo.examview.test.api.TestApi;
import com.lancoo.examview.test.entity.testEntity.ApiResponse;

import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lancoo.com.net.retrofitrxjava.NetworkTransformer;
import lancoo.com.net.retrofitrxjava.download.UpLoadPart;
import lancoo.com.net.retrofitrxjava.download.UploadProgressListener;
import lancoo.com.net.retrofitrxjava.network.Network;
import lancoo.com.net.retrofitrxjava.subscriber.NormalSubscriber;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * Created by pengmi on 2021/12/9 18:37
 * Description:
 */
public class PaperPresenter {


    //上传时进度回调监听
    private UploadProgressListener uploadProgressListener=new UploadProgressListener() {
        @Override
        public void onProgress(long currentBytesCount, long totalBytesCount) {
            int progress= (int) ((currentBytesCount+0f)/totalBytesCount*100);
            Log.e("aaaaaaa","upload progress:"+progress);
        }
    };

    private RequestBody convertToRequestBody(String param){
        RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain"), param);
        return requestBody;
    }


    /**
     * 上传图片
     * @param imgs list
     * @param imageEvent bean
     */
    public void uploadImages(List<String> imgs,final ImageEventBean imageEvent){
        if(imgs==null||imgs.size()==0) {
            return;
        }
        //这里进行压缩和旋转处理
        List<MultipartBody.Part> parts = new ArrayList<>();
        for (int i = 0; i < imgs.size(); i++) {
            File file = new File(imgs.get(i));
            MultipartBody.Part part = UpLoadPart.getInstance().getPart(file, System.currentTimeMillis()+"file" + i, true, uploadProgressListener);
            parts.add(part);
        }
        if (parts.size() == 0) {
            return;
        }
        //teachBookId=be1408ac-d1f5-46c2-9055-810b62940e0c&materialID=
        Map<String, RequestBody> params = new HashMap<>();
        //以下参数是伪代码，参数需要换成自己服务器支持的
        Network.getJsonData(TestApi.class, "http://122.9.115.176:10110/Web_AITeachCloudV10/")
                .uploadAudioFiles(parts,"123","123","123")
                .compose(NetworkTransformer.<ApiResponse<List<String>>>commonSchedulers())
                .subscribe(new NormalSubscriber<ApiResponse<List<String>>>(){
                    @Override
                    public void onNext(@NotNull ApiResponse<List<String>> multimediaResponce) {
                        super.onNext(multimediaResponce);
                        Log.e("aaaaaa","onNext");
                        List<String> urlList=new ArrayList<>();
                        if(multimediaResponce.getStatus()==1&&multimediaResponce.getData()!=null){
                            String baseUrl="https://obs-79f-artificial-intelligence.obs.cn-east-2.myhuaweicloud.com/";
                            for (String string:multimediaResponce.getData()){
                                urlList.add(baseUrl+string);
                                Log.e("url",""+baseUrl+string);
                            }
                        }

                        uploadCallBack(true,urlList,imageEvent);
                    }
                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        Log.e("aaaaaa","error");
//                        mLoading.dismiss();
                        uploadCallBack(false,null,imageEvent);
                    }
                });



    }

    /**
     * 音频上传
     * @param eventBean bean
     */
    public void uploadAudioPath( AudioUpLoadEventBean eventBean){
        String audioLocalPath = eventBean.getAudioLocalPath();
        //这里进行压缩和旋转处理
        File file = new File(audioLocalPath);
        MultipartBody.Part part = UpLoadPart.getInstance().getPart(file, "file" +System.currentTimeMillis(), true, uploadProgressListener);
        //teachBookId=be1408ac-d1f5-46c2-9055-810b62940e0c&materialID=
        Map<String, RequestBody> params = new HashMap<>();
        //以下参数是伪代码，参数需要换成自己服务器支持的
        Network.getJsonData(TestApi.class, "http://122.9.115.176:10110/Web_AITeachCloudV10/")
                .uploadAudioFile(part,"123","123","123")
                .compose(NetworkTransformer.<ApiResponse<List<String>>>commonSchedulers())
                .subscribe(new NormalSubscriber<ApiResponse<List<String>>>(){
                    @Override
                    public void onNext(@NotNull ApiResponse<List<String>> multimediaResponce) {
                        super.onNext(multimediaResponce);
                        Log.e("aaaaaa","onNext");
                        String audioPath="";
                        if(multimediaResponce.getStatus()==1&&multimediaResponce.getData()!=null){
                            String baseUrl="https://obs-79f-artificial-intelligence.obs.cn-east-2.myhuaweicloud.com/";
                            for (String string:multimediaResponce.getData()){
                                audioPath=baseUrl+string;
                                Log.e("url",""+baseUrl+string);
                            }
                        }
                        uploadCallBack(true,audioPath,eventBean);

//                        uploadCallBack(true,urlList,imageEvent);
                    }
                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        Log.e("aaaaaa","error");
//                        uploadCallBack(false,null,imageEvent);
                        uploadCallBack(false,"",eventBean);
                    }
                });



    }

    /**
     * 图片上传执行Event回调
     * @param isSucess
     * @param imgUrls
     * @param imageEvent
     */
    private void uploadCallBack(boolean isSucess,List<String> imgUrls,ImageEventBean imageEvent){
        ImageCallBackEventBean callBackEventBean=new ImageCallBackEventBean();
        callBackEventBean.setImgList(imgUrls);
        callBackEventBean.setChildIndex(imageEvent.getChildIndex());
        callBackEventBean.setTypeIndex(imageEvent.getTypeIndex());
        callBackEventBean.setQueseIndex(imageEvent.getQueseIndex());
        callBackEventBean.setItemIndex(imageEvent.getItemIndex());
        callBackEventBean.setSuccess(isSucess&&(imgUrls!=null&&imgUrls.size()>0));
        EventBus.getDefault().post(callBackEventBean);
    }

    /**
     * 音频上传执行Event回调
     * @param isSucess
     * @param audioPath
     * @param upLoadEventBean
     */
    private void uploadCallBack(boolean isSucess,String audioPath,AudioUpLoadEventBean upLoadEventBean){
        AudioUpLoadCallBackEventBean callBackEventBean=new AudioUpLoadCallBackEventBean();
        callBackEventBean.setAudioPath(audioPath);
        callBackEventBean.setChildIndex(upLoadEventBean.getChildIndex());
        callBackEventBean.setTypeIndex(upLoadEventBean.getTypeIndex());
        callBackEventBean.setQueseIndex(upLoadEventBean.getQueseIndex());
        callBackEventBean.setItemIndex(upLoadEventBean.getItemIndex());
        callBackEventBean.setSuccess(isSucess&&!TextUtils.isEmpty(audioPath));
        EventBus.getDefault().post(callBackEventBean);
    }
}
